<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    
    <title>Map</title>
    
    <script type="text/javascript" src="js/echarts.min.js"></script>
    <script type="text/javascript" src="data/scatterData.js"></script>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <style>
        html, body {
            margin:0px;
            height:100%;
            width:100%
        }
        .container {
            width:90%;
            height: 90%
        }
        .axis path,
        .axis line{
            fill: none;
            border: 1px solid #eee;
            stroke: #999;
            shape-rendering: crispEdges;
        }
        #main { width: calc(100% - 100px);}
        
    </style>
  </head>
  <body>
    <div style="position: fixed; left: 20px; top: 30px;">
        宽度：<input type="value" id="maxWidth" style="height:25px; width: 60px; margin-right: 5px" value="35000" />
        高度：<input type="value" id="maxHeight" style="height:25px; width: 60px; margin-right: 5px" value="1200" />
        柱宽：<input type="value" id="barWidth" style="height:25px; width: 60px; margin-right: 5px" value="1" />
        最大值：<input type="value" id="maxValue" style="height:25px; width: 60px; margin-right: 5px" />
        间距：<input type="value" id="distance" style="height:25px; width: 60px; margin-right: 5px" />

        <button style="width: 60px; color: #f00; font-size: 16px; height: 30px" onclick="setMaxValue()">重绘</button>
    </div>
    <div id="Sections" style="height: 60px; width: 100%; padding-top: 40px; text-align: end;"></div>
    <div id="main" style="height: 95%; padding-left: 100px;overflow-x: hidden;">
        <div id="view" class="container" style="height: 100%; width: 100%; overflow: hidden; border: 0px solid #ccc">
        </div>    
    </div>
    
    <script>
        let keys = Object.keys(scatters);
        let htmls = keys.map(k => "<span style='border: 1px solid #ccc; padding: 5px 10px; color: blue; cursor: pointer; margin-right: 10px' onclick='loadSection(" + k.toString() + ")'>" + k + "</span>").join("");
        document.getElementById("Sections").innerHTML = htmls;
        let MAX_C = 0;
        let MAX_V = 0;
        let DIS = 1;
        let BAR_W = 1;
        let SECTION = {};
        let DATAS = {};

        // let myChart = echarts.init(document.getElementById("view"));
        // let option = getOption();
        // myChart.setOption(option);
        // loadSection(keys[0].replace("_", ""));
        
        draw(keys[0].replace("_", ""));

        function loadSection(k) {
            return draw(k);

            let ps = k.toString().split('').join("_");
            let section = scatters[ps];
            console.log(section);
            let option = getOption(section);
            console.log(option);
            myChart.setOption(option);
        }

        // 合并数据到区间
        function mergedata (dt, dis) {
            let keys = Object.keys(dt);
            let maxLen = keys.reduce((a, b) => dt[b].length > a ? dt[b].length : a, 0);
            if (!dis) {
                dis = parseInt(maxLen > 5000 ? (maxLen / 2500) : 1);
                document.getElementById("distance").value = dis;
            }
            let dts = {};
            keys.forEach(k => {
                lines = [];
                let ary = dt[k].map(d => d[0]).sort((a, b) => a - b);
                ary.forEach((d, i) => {
                    let idx = parseInt(d / dis);
                    if (!lines[idx]) {
                        lines[idx] = [idx * dis + dis / 2, d, d, 1];
                    } else {
                        lines[idx][2] = d;
                        lines[idx][3] += 1;
                    }
                });
                dts[k] = lines;
            })
            return dts;
        }

        function getMaxValue (dts) {
            let maxV = 0;
            let maxC = Object.keys(dts).reduce((m, k) => {
                let x = dts[k].reduce((a, b) => a > b[3] ? a : b[3], 0);
                let last = dts[k][dts[k].length - 1];
                if (maxV < last[2]) maxV = last[2];
                return x > m ? x : m
            }, 0);
            return [maxC, maxV];
        }

        function setMaxValue() {
            MAX_V = parseInt(document.getElementById("maxValue").value);
            DIS = parseInt(document.getElementById("distance").value);
            BAR_W = parseInt(document.getElementById("barWidth").value);
            DATAS = mergedata(SECTION, DIS);
            MAX_C = getMaxValue(DATAS)[0];
            drawScatterD3();
        }

        function draw (k) {
            document.getElementById("view").innerHTML = "";
            let ps = k.toString().split('').join("_");
            SECTION = scatters[ps];

            DATAS = mergedata(SECTION);
            [MAX_C, MAX_V] = getMaxValue(DATAS);
            document.getElementById("maxValue").value = MAX_V;
            drawScatterD3();
        }
        function drawScatterD3() {
            document.getElementById("view").innerHTML = "";
            let [maxC, maxV] = [MAX_C, MAX_V];
            let dts = DATAS;
            let count = Object.keys(dts).length;
            let maxH = maxC / count;
            let H = parseInt(document.getElementById("maxHeight").value)
            let W = parseInt(document.getElementById("maxWidth").value)
            let padding = 50;

            let zoom = d3.zoom().scaleExtent([1, 100]).on("zoom", () => {
                svg.attr("transform", "translate(" + d3.event.transform.x + "," + d3.event.transform.y + ")scale(" + d3.event.transform.k + ")");
            });
            let xScale = d3.scaleLinear().domain([0, maxV]).range([0, W]);    
            let yScale = d3.scaleLinear().domain([maxC, 0]).range([0, H]);
            let yScale2 = d3.scaleLinear().domain([0, maxC]).range([0, H / count]);
            let xAxis = d3.axisBottom(xScale).ticks(100);
            let yAxis = d3.axisLeft(yScale);
            
            console.log(maxC, maxV);

            svg = d3.select("#view")
                .append("svg")
                .attr("width", W)
                .attr("height", H + padding)
                .attr("style", "border:1px solid #00f;")
                .call(zoom);
            let group = svg.append("g").attr("transform", "translate(50, -10)");
            group.append("g").attr("class", "axis").attr("transform", "translate(0, 0)").call(yAxis);
            group.append("g").attr("class", "axis").attr("transform", "translate(0, " + H + ")").call(xAxis);

            // 柱状图
            Object.keys(dts).forEach((k, i) => {
                group.append("g").selectAll("rect").data(dts[k].filter(d => d)).enter().append("rect")
                    .attr("x", d => xScale(d[2]))
                    .attr("y", d => H / count * (i + 1) - yScale2(d[3]))
                    .attr("width", BAR_W)
                    .attr("height", d => yScale2(d[3]))
                    .style("fill", "#00f")
                    .on("click", d => {
                        console.log(d);
                    });
            });

            // 散点图
            Object.keys(SECTION).forEach((t, i) => {
                let g = group.append("g");
                g.selectAll("circle")
                    .data(SECTION[t]).enter()
                    .append("circle")
                    .attr("cx", d => xScale(d[0]))
                    .attr("cy", d => H / count * (i + 1) + 10)
                    .attr("r", 1)
                    .attr("fill", d => "red")
                    .on("click", d => {
                        console.log(d);
                    });
            });

            
        }

        function getOption (dt) {
            let option = {
                color: ['#dd4444', '#fec42c', '#80F1BE'],
                legend: {
                    top: 10,
                    data: Object.keys(dt),
                    textStyle: {
                        fontSize: 16
                    }
                },
                grid: {
                    left: 100,
                    right: 50,
                    top: '5%',
                    bottom: 50
                },
                tooltip: {
                    backgroundColor: 'rgba(255,255,255,0.7)',
                    formatter: function (param) {
                        let value = param.value;
                        return '';
                    }
                },
                xAxis: {
                    type: 'value',
                    name: '行驶时间',
                    nameGap: 16,
                    nameTextStyle: {
                        fontSize: 16
                    }
                    
                },
                yAxis: {
                    type: 'value',
                    name: '车型',
                    nameLocation: 'end',
                    nameGap: 20,
                    max: 21,
                    nameTextStyle: {
                        fontSize: 16
                    },
                    splitLine: {
                        show: false
                    }
                },
                series: Object.keys(dt).map(k => ({
                    name: k,
                    type: 'scatter',
                    symbolSize: 5,
                    data: dt[k]
                }))
            };
            return option;
        }
        
    </script>
  </body>
</html>  